// src/services/WebSocketService.js
export default class WebSocketService {
    constructor(url) {
        this.url = url;
        this.socket = null;
        this.listeners = {};
        this.connect();
    }

    connect() {
        if (this.socket) {
            this.socket.close();
        }

        this.socket = new WebSocket(this.url);

        this.socket.onopen = () => {
            console.log('WebSocket 连接已打开');
            this.emit('open');
            this.startHeartbeat();
        };

        this.socket.onmessage = (event) => {
            const data = JSON.parse(event.data);
            console.log('收到 WebSocket 消息:', data);
            this.emit('message', data);
        };

        this.socket.onerror = (error) => {
            console.error('WebSocket 错误:', error);
            this.emit('error', error);
        };

        this.socket.onclose = (event) => {
            console.log('WebSocket 连接已关闭', event);
            this.stopHeartbeat();
            this.reconnect();
            this.emit('close', event);
        };
    }

    send(data) {
        if (this.socket.readyState === WebSocket.OPEN) {
            this.socket.send(JSON.stringify(data));
        } else {
            console.warn('WebSocket 不可用，无法发送消息');
        }
    }

    on(event, callback) {
        if (!this.listeners[event]) {
            this.listeners[event] = [];
        }
        this.listeners[event].push(callback);
    }

    off(event, callback) {
        if (this.listeners[event]) {
            this.listeners[event] = this.listeners[event].filter(cb => cb !== callback);
        }
    }

    emit(event, data) {
        if (this.listeners[event]) {
            this.listeners[event].forEach(callback => callback(data));
        }
    }

    startHeartbeat() {
        this.heartbeatInterval = setInterval(() => {
            if (this.socket.readyState === WebSocket.OPEN) {
                this.socket.send(JSON.stringify({ type: 'heartbeat' }));
            }
        }, 30000); // 每30秒发送一次心跳
    }

    stopHeartbeat() {
        clearInterval(this.heartbeatInterval);
    }

    reconnect() {
        console.log('尝试重新连接 WebSocket...');
        setTimeout(() => {
            this.connect();
        }, 5000); // 5秒后重新连接
    }
}
